package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.prefs.BackingStoreException;
import java.util.stream.Collectors;


@RestController
@RequestMapping("setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;


    /**
     * 套餐信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name) {

        //构造分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        //构造查询构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //添加查询条件
        lqw.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        //添加排序条件
        lqw.orderByDesc(Setmeal::getUpdateTime);
        //拷贝数组，排除菜品信息集合
        setmealService.page(pageInfo,lqw);
        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, setmealDtoPage, "records");
        //给套餐内菜品集合重新赋值
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> list = records.stream().map((item) -> {
            //创建一个SetmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            //复制dish数据到setmealDto
            BeanUtils.copyProperties(item, setmealDto);
            //获取分类id
            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            //判断是否获取对象
            if (category != null) {
                //赋值菜品分类名称
                String name1 = category.getName();
                setmealDto.setCategoryName(name1);
            }
            return setmealDto;

        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);
        //把封装的带有分类名称的集合赋值给setmealDto集合
        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐(批量)
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam  List<Long> ids){
        log.info("ids:{}",ids);
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
    }

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("setmealDto:{}",setmealDto);
        setmealService.saveSetmeaWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /**
     *查询套餐信息
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal){
        //构造查询构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件（套餐）
        queryWrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        //添加查询条件（启售）
        queryWrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行查询
        List<Setmeal> list = setmealService.list(queryWrapper);
        return R.success(list);
    }

    /**
     * 根据id查询套餐信息及菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        log.info("id:{}",id);
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 停售起售（批量）
     * @param type
     * @param ids
     * @return
     */
    @PostMapping("/status/{type}")
    public R<String> updateType(@PathVariable int type,@RequestParam List<Long> ids){
        //构造查询构造器
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        //添加查询条件
        lqw.in(Setmeal::getId,ids);
        //执行查询
        List<Setmeal> setmealList = setmealService.list(lqw);
        //添加查询条件
        lqw.eq(Setmeal::getStatus,type);
        //统计不符合状态的数据
        int count = setmealService.count(lqw);
        if (count == 0){
            //符合条件，进行状态修改
            setmealList.forEach(setmeal -> {
                setmeal.setStatus(type);
            });
            setmealService.updateBatchById(setmealList);
            return R.success("状态修改成功");
        }else {
            throw new CustomException("所选套餐状态不一致");

        }
    }

    /**
     * 修改套餐内容
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateSetmealWithDish(setmealDto);
        return R.success("修改成功");
    }
    /**
     * 查看套餐详情
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<SetmealDish>>dish(@PathVariable Long id){
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> dishList = setmealDishService.list(lqw);
        return R.success(dishList);
    }
}
